<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use DB;
use Redis;

//局域网计划任务
class TimerController extends Controller
{
    public function timer(){
        set_time_limit(0);
        ini_set('max_execution_time', 0);
        ini_set('memory_limit', '-1');
        //每隔n分钟请求一次温湿度大气压
        $this->getEnv();
    }
    private function getEnv(){
        info('温湿度获取');
        ini_set("default_socket_timeout",1);
        // $devs = DB::table('a_hb6303')->where('tcp_type','tcp server')->get();
        $devs = DB::table('a_hb6303')->where('tcp_type','tcp server')->get();
        if (!$devs) {
            return false;
        }
        // $devs = json_decode(json_encode([['send_hex'=>"00 00 00 00 00 06 01 03 00 00 00 02",'ip_port'=>'192.168.8.181:8000']]));  //温湿度：00 00 00 00 00 06 01 03 00 00 00 02；大气压、温湿度大气压：01 03 00 00 00 03 05 CB
        foreach ($devs as $item) {
            $this->upEnv($item);
            sleep(5); //因为一直请求socket容易没反应，所以这里间隔10s
        }
    }

    public function upEnv($item){
        $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname("tcp"));  // 创建Socket
        try{
            $sendStr = '0x'.$item->send_hex;
            $ip_port = explode(':',$item->ip_port);
            $ip = $ip_port[0];
            $port = $ip_port[1];
            if (!$sendStr || !$ip || !$port) {
                return;
            }

            $sendStr = str_replace(' ', '', $sendStr);
            $isHex = substr($sendStr,0,2) == '0x';  //判断是否是16进制
            if ($isHex) {
                $sendStr = substr($sendStr,2);
                $sendStr16 = implode(' ', str_split($sendStr, 2));
                $sendStr = hex2bin(preg_replace('# #', '', $sendStr16));
                // info("16进制数据:$sendStr");
                // echo '16进制数据:'.$sendStr.' \r\n';
            }
            $connection = socket_connect($socket, $ip, $port);
            // $connection = socket_connect($socket, "192.168.8.181", 8000);
            info("连接状态：$connection");
            // echo "连接状态：$connection \n";
            if ($connection) {  //连接
                // for ($j = 0; $j < count($sendStrArray); $j++) {
                //     socket_write($socket, chr(hexdec($sendStrArray[$j])));  // 逐组数据发送
                // }

                //向打开的套集字写入数据（发送数据）
                $st=$sendStr;
                $length = strlen($st);
                $s = socket_write($socket, $st, $length);
                //从套接字中获取服务器发送来的数据
                $msg = socket_read($socket,8190);
                if ($isHex) {
                    $msg = bin2hex($msg);
                }
                info("16进制返回数据");
                // echo $msg;
                $humi = $temp = $pressure = '';
                // info(substr($msg,0,18));
                // if(substr($msg,0,-8) === '000000000007010304') //温湿度
                switch($item->type){
                    case 'temp_hum':
                        // code...
                        $humi = hexdec(substr($msg,-8,-4))/10;
                        // info($hui);
                        $temp = strtolower(substr($msg,-4,2)) == 'ff' ? hexdec(substr($msg,-2))/10 : hexdec(substr($msg,-4))/10;
                        // info($tem);
                        break;
                    case 'press':
                        $pressure = hexdec(substr($msg,6,4))/10;
                        // info(substr($msg,6,4));
                        $temp = strtolower(substr($msg,10,2)) == 'ff' ? hexdec(substr($msg,12,2))/10 : hexdec(substr($msg,10,4))/10;
                        // info(substr($msg,10,4));
                        break;
                    default:
                        $humi = hexdec(substr($msg,6,4))/10;
                        // info(substr($msg,6,4));
                        $temp = strtolower(substr($msg,10,2)) == 'ff' ? hexdec(substr($msg,12,2))/10 : hexdec(substr($msg,10,4))/10;
                        // info(substr($msg,10,4));
                        $pressure = hexdec(substr($msg,14,4))/10;
                }
                if ($humi || $temp || $pressure ) {
                    DB::table('a_env_info')->insert([
                        'temp' => $temp,
                        'humi' => $humi,
                        'pressure' => $pressure,
                        'hb6303_id'=>$item->id,
                        'dev_num'=>$item->dev_num
                    ]);
                }
                info("温湿度设备获取数据：$msg");
                info("温湿度设备：$item->dev_num");
                // echo $msg." \n";
            }
        }catch(\Exception $exception){
            // dd($exception->getMessage(),$exception->getLine());
            info('温湿度设备获取数据有误：'.$exception->getMessage().',行号：'.$exception->getLine());
        }
        socket_close($socket);  // 关闭Socket
    }
}
